﻿
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WHLRDF.Application.BLL;
using WHLRDF.Application.Model;
using WHLRDF.Cache;

namespace WHLRDF.Web.Controllers
{

    public class SSOController : BaseController
    {
        public IUserService service { get; set; }

        [HttpPost]
        public async Task<JsonResult> Login(string userName, string password,string ticked, string token)
        {
            string strError = "";
            if (!MD5Helper.GetToken(userName + password+ ticked).ToLower().Equals(token))
            {
                return  Json(AjaxResult.Error("参数值不正确"));
            }
            token = "";
           
            string access_token = "";
            var result = service.Login(userName, password, ref strError, ref access_token);
            if (result != null)
            {
                var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name,result.UserName) ,
                        new Claim(ClaimTypes.GivenName,result.RealName) ,
                        new Claim(ClaimTypes.MobilePhone,result.Phone),
                        new Claim(ClaimTypes.Email,result.Email) ,
                         new Claim(ClaimTypes.Authentication,access_token) ,
                        new Claim(ClaimTypes.NameIdentifier,result.UserId.ToString())

                    };
                await SignInAsync(claims, result.UserId.ToString(), access_token, false);

                return Json(AjaxResult.Success(new { access_token = access_token }));
            }
            return Json(AjaxResult.Error(strError));


        }
        public JsonResult Refresh(string access_token)
        {
            if (CacheHelper.CacheService.Exists(ApplicationEnvironments.Site.UserCacheKey + access_token))
            {
                CacheHelper.CacheService.Refresh(ApplicationEnvironments.Site.UserCacheKey + access_token);
                return Json(AjaxResult.Success());
            }
            return Json(AjaxResult.Error("令牌已过期或不存在"));
        }
        public JsonResult GetUserInfo( string access_token)
        {
            var result = CacheHelper.CacheService.GetCache<UserEntity>(ApplicationEnvironments.Site.UserCacheKey + access_token);
            if (result != null)
            {
                return Json(AjaxResult.Success(new {UserName=result.UserName, RealName=result.RealName, Sex=result.Sex,Phone=result.Phone,Email=result.Email }));
            }
            return Json(AjaxResult.Error("令牌已过期"));
        }
    }
}